package context;

import bean.UserInfo;
import io.netty.channel.Channel;
import message.Message;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wb_zhulinzhong
 * @date 2021-04-14 17:20:09
 */
public class ComServerContext {

    private final Map<String, Channel> channelCacheByChannelId = new HashMap<>();
    private final Map<UserInfo, Channel> channelCacheByUserId = new HashMap<>();


    private static final ComServerContext comContext = new ComServerContext();

    private ComServerContext(){ }

    public static ComServerContext comContext(){
        return comContext;
    }

    public Map<String, Channel> getChannelCacheByChannelId() {
        return channelCacheByChannelId;
    }

    public Channel getChannelCacheByUserId(UserInfo userInfo) {
        return channelCacheByUserId.get(userInfo);
    }

    public void addChannelCacheByChannelId(String channelId, Channel channel){
        this.channelCacheByChannelId.put(channelId, channel);
    }

    public void addChannelCacheByUserId(UserInfo userInfo, Channel channel){
        this.channelCacheByUserId.put(userInfo, channel);
    }


    /**
     * 服务端发送消息
     * @param message
     */
    public void serverSendMessageToClient(Message message){
        this.channelCacheByChannelId.forEach((channelId, channel) ->{
            channel.writeAndFlush(message);
        });
    }

    /**
     * 服务端发送消息
     * @param message
     * @param clientId
     * @param <T>
     */
    public void serverSendMessageToClientByClientId(Message message, String clientId){
        Channel channel = this.channelCacheByChannelId.get(clientId);
        if(channel != null){
            channel.writeAndFlush(message);
        }
    }

    /**
     * 服务端发送消息
     * @param message
     * @param userId
     * @param <T>
     */
    public void serverSendMessageToClientByUserId(Message message, String userId){

    }
}
